<template>
  <q-page class='flex flex-center'>
    <q-card bordered class='login-card'>
      <q-card-section>
        <div class='text-center'>
          <q-avatar>
            <img :src='logo' alt='加载失败' />
          </q-avatar>
        </div>
      </q-card-section>
      <q-tab-panel>
        <q-form class='q-pa-md q-gutter-md' ref='form' @submit='login'>
          <q-input v-model='state.username' label='用户名' dense :rules='rules.username' />
          <q-input v-model='state.password' label='密码' dense :rules='rules.password'
                   :type="isPwd ? 'password' : 'text'">
            <template #append>
              <q-icon
                :name="isPwd ? 'visibility_off' : 'visibility'"
                class='cursor-pointer'
                @click='isPwd = !isPwd'
              />
            </template>
          </q-input>
          <div>
            <q-btn push label='登 录' type='submit' class='fit' color='primary' />
          </div>
        </q-form>
        <q-tabs dense>
          <q-space />
          <q-route-tab label='是新用户？点击注册' to='/auth/register' class='text-primary' />
          <q-space />
        </q-tabs>
      </q-tab-panel>
    </q-card>
  </q-page>
</template>

<script lang='ts'>
import { defineComponent, ref } from 'vue';
import _logo from 'assets/logo.png';
import { FieldRule } from 'app/typings';
import { useRouter } from 'vue-router';
import { signIn } from 'src/services/api';
import { required } from 'src/services/validator';

const logo = _logo as string;
const isPwd = ref(true);

export default defineComponent({
  name: 'Login',
  setup() {
    const router = useRouter();
    const state = ref({
      username: '',
      password: ''
    });
    const rules = {
      username: <FieldRule[]>[val => required(val, '请输入用户名')],
      password: <FieldRule[]>[val => required(val, '请输入密码')]
    };
    const login = async () => {
      try {
        const result = await signIn(state.value.username, state.value.password);
        if (result) {
          await router.push('/home');
        }
      } catch (error) {
      }
    };

    return {
      logo,
      isPwd,
      state,
      rules,
      login
    };
  }
});
</script>

<style scoped lang='scss'>
.login-card {
  width: 100%;
  max-width: 400px;
  height: 100%;
  max-height: 650px;
}
</style>
